<template>
  <!-- 验证码 -->
  <div class="m-custom-validecode">
    <canvas ref="Jcanvas" width="154" height="54" @click="createCode()"></canvas>
  </div>
</template>

<script>
export default {
  data () {
    return {
      code: ''
    }
  },
  mounted () {
    this.createCode()
  },
  methods: {
    createCode (codelength) {
      let code = ''
      let codeLength = parseInt(codelength) || 4  // 验证码长度

      /// /所有候选组成验证码的字符，也可用中文
      let codeChars = [
        0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
      ]
      // 循环组成验证码的字符串
      for (let i = 0; i < codeLength; i++) {
        // 获取随机验证码下标
        let charNum = Math.floor(Math.random() * codeChars.length)
        // 组合成指定字符验证码
        code += codeChars[charNum]
      }
      this.code = code
      // 将生成验证码赋值到显示区
      this.show(code)
    },

    show (show_num) {
      var canvas_width = this.$refs.Jcanvas.offsetWidth
      var canvas_height = this.$refs.Jcanvas.offsetHeight
      var canvas = this.$refs.Jcanvas
      var context = canvas.getContext('2d')
      canvas.width = canvas_width
      for (var i = 0; i < show_num.length; i++) {
        var deg = (Math.random() * 30 * Math.PI) / 180
        var text = show_num.charAt(i)
        var x = i * 28 + 10  // 文字在canvas上x坐标
        var y = 30  // 文字在canvas上y坐标

        context.font = 'bold 25px 微软雅黑'
        context.translate(x, y)
        context.rotate(deg)

        context.fillStyle = this.randomColor()
        context.fillText(text, 0, 0)

        context.rotate(-deg)
        context.translate(-x, -y)
      }

      for (var j = 0; j <= 5; j++) {
        // 验证码上显示线条
        context.strokeStyle = this.randomColor()
        context.beginPath()
        context.moveTo(
          Math.random() * canvas_width,
          Math.random() * canvas_height
        )
        context.lineTo(
          Math.random() * canvas_width,
          Math.random() * canvas_height
        )
        context.stroke()
      }
    },
    randomColor () {
      for (var k = 0; k <= 30; k++) {
        // 验证码上显示小点
        var r = Math.floor(Math.random() * 256)
        var g = Math.floor(Math.random() * 256)
        var b = Math.floor(Math.random() * 256)
        return 'rgb(' + r + ',' + g + ',' + b + ')'
      }
    }
  }
}
</script>

<style>
.m-custom-validecode {
  width: 100%;
  height: 54px;
}
</style>